// packageBook/pages/appointHistory/appointHistory.js
const requestUtil = require('../../../utils/requestUtil')
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    app:app,
    havaBookDatas:true,
    dialogTitle:"确定要取消预约吗？",
    showQrcode: false,
    qrCodeUrl: 'https://xit-edu.cn/oss/appointMiniImg/BookVisit/icon_down.png',
    deleteId: '',
    deleteType: '',
    showDialog: false,
    currentSelectTitle: "我的预约",
    topList: ['我的预约', '历史记录'],
    bookDatas: [{
      "appointmentId": 0,
      "userId": null,
      "slotId": 1,
      "appointmentDate": "2024-11-10",
      "createdTime": "2024-11-06",
      "isCheckedIn": 0,
      "delFlag": 0,
      "deptId": null,
      //额外加
      "showDetail": false,
      "appointmentTime": "10:00-12:00", //根据slotId  appointmentDate也要处理
      "detail": [{
        "detailId": 43,
        "appointmentId": 0,
        "name": "value1",
        "idNumber": "value2",
        "carId": "value3",
        "qrUrl": "http://visit-vit.oss-cn-beijing.aliyuncs.com/4349a479-9a48-4874-839b-4ea91762b9c3.png"
      }]
    }],
    bookDatasHistory: [],
  },
  showQrcode(e) {
    this.setData({
      showQrcode: true,
      qrCodeUrl: 'https://xit-edu.cn' + e.currentTarget.dataset.url.replace('home', '')
    })
    // console.log()
  },
  hideQrcode() {
    this.setData({
      showQrcode: false
    })
  },
  getAllbookDatas() {
    wx.showLoading({
      title: 'Loading...',
    })
    this.setData({
      bookDatas: []
    })
    const _this = this
    requestUtil.requestRe('appointment/list?pageNumb=1&pageSize=10000', 'Get')
      .then((responseData) => {
        this.setData({
          err:false
        })
        if (responseData.rows.length ==0) {
          _this.setData({
            havaBookDatas:false
          })
        }
        
        //区分有没有过期
        //当前日期
        const currentDate = new Date();
        // 用于存储分组结果的对象
        const groupedAppointments = {
          expired: [],
          upcoming: []
        };
        const appointDatas = responseData.rows.slice().reverse();
        // 遍历预约数据
        appointDatas.forEach(appointment => {
          const appointmentDateObj = new Date(appointment.appointmentDate);
          // 对应的区间数字转化
          if (appointment.slotId  == 0) {
            appointmentDateObj.setHours(10);
          } else if (appointment.slotId  == 1) {
            appointmentDateObj.setHours(12);
          } else if (appointment.slotId  == 2) {
            appointmentDateObj.setHours(14);
          } else if (appointment.slotId  == 3) {
            appointmentDateObj.setHours(16);
          } else if (appointment.slotId  == 4) {
            appointmentDateObj.setHours(18);
          }

          if (appointmentDateObj < currentDate) {
            this.getDetailDataByAppointmentId({
              id: appointment.appointmentId,
              type: '已过期',
              appointment: appointment
            })
            // groupedAppointments.expired.push(appointment);

          } else if (appointmentDateObj >= currentDate) {
            this.getDetailDataByAppointmentId({
              id: appointment.appointmentId,
              type: '未过期',
              appointment: appointment
            })
            // groupedAppointments.upcoming.push(appointment);
          }
        });

        // console.log(groupedAppointments.upcoming)
        this.setData({
          bookDatas: groupedAppointments.upcoming,
          bookDatasHistory: groupedAppointments.expired
        })
      })
      .catch((err) => {
        this.setData({
          err:true
        })
        wx.showModal({
          title: '请求失败',
          content: err,
        })
      })

  },
  //获取详细数据
  getDetailDataByAppointmentId(e) {
    wx.showLoading({
      title: 'Loading...',
    })
    //这个是存appointmentId
    const datas = e
    requestUtil.requestRe('appointment/detailList/' + e.id, 'Get')
      .then((responseData) => {
        if (datas.type == '未过期') {
          //对数据赋值 详细数据
          const tempdata = this.data.bookDatas
          datas.appointment['detail'] = responseData.rows
          if (responseData.rows.length == 0) {
            // 把没有预约细节的（没有了预约人）的删掉
            this.deleteAppointMethod(e.id)
          }
          //日期格式修改
          datas.appointment['appointmentDate'] = datas.appointment['appointmentDate'].replace("-", "/").replace(/^20/, "").replace("-", "/")
          datas.appointment['appointmentTime'] = this.timeFormat(datas.appointment['slotId'])
          tempdata.push(datas.appointment)
          this.setData({
            bookDatas: tempdata
          })
        } else if (datas.type == '已过期') {
          const tempdata = this.data.bookDatasHistory
          datas.appointment['detail'] = responseData.rows
          //日期格式修改
          datas.appointment['appointmentDate'] = datas.appointment['appointmentDate'].replace("-", "/").replace(/^20/, "").replace("-", "/")
          datas.appointment['appointmentTime'] = this.timeFormat(datas.appointment['slotId'])

          if (responseData.rows.length == 0) {
            // 把没有预约细节的（没有了预约人）的删掉
            this.deleteAppointMethod(e.id)
          }
          
          tempdata.push(datas.appointment)
          this.setData({
            bookDatasHistory: tempdata
          })
        }

      })
  },
  //日期转化
  timeFormat(e) {
    const timeRanges = ['8:00 - 10:00', '10:00 - 12:00', '12:00 - 14:00', '14:00 - 16:00', '16:00 - 18:00']
    return timeRanges[e]
  },
  //是否删除  来自dialog传递过来的确认 和 取消
  dialogMethod(e) {
    this.setData({
      showDialog: false
    })
    if (e.detail.value == 'confirm') {
      if (this.data.deleteType == 'appointmentId') {
        this.deleteAppointMethod(this.data.deleteId)
      } else if (this.data.deleteType == 'detailId') {
        this.deleteDetailMethod(this.data.deleteId)
      }
    } else if (e.detail.value == 'cancel') {
      console.log('取消删除')
    }
  },
  //删除函数
  deleteAppointMethod(e) {
    // console.log(e)
    requestUtil.requestRe('appointment/' + e, 'Delete')
      .then((responseData) => {
        console.log(responseData)
        this.getAllbookDatas()
      })
      .catch((error) => {
        console.log('失败，错误信息：', error);
      });
  },
  //删除细节函数
  deleteDetailMethod(e) {
    // console.log(e)
    requestUtil.requestRe('appointment/detailList/' + e, 'Delete')
      .then((responseData) => {
        console.log(responseData)
        this.getAllbookDatas()
      })
      .catch((error) => {
        console.log('失败，错误信息：', error);
      });
  },
  showDialogAppoint(e) {
    this.setData({
      showDialog: true,
      deleteId: e.currentTarget.dataset.info,
      deleteType: e.currentTarget.dataset.type
    })
  },
  showDetail(e) {
    //细节
    const index = e.currentTarget.dataset.info
    let newDetail = this.data.bookDatas
    newDetail[index].showDetail = !newDetail[index].showDetail
    this.setData({
      bookDatas: newDetail
    })
  },
  selectTop(e) {
    this.setData({
      currentSelectTitle: e.currentTarget.dataset.info
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getAllbookDatas()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
